import { http, downloadBlob } from '@/utils/http'
import { message } from '@/utils/message'
import type { AxiosHeaders } from 'axios'
import { ElLoading } from 'element-plus'

/**
 * 批量下载
 * @param url
 * @param params
 * @returns
 */
export const commonExportListToExcel = (url, params) => {
  const downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  return http
    .post<{}, { data: Blob; headers: AxiosHeaders }>(url, {
      params,
      responseType: 'blob',
    })
    .then((res) => {
      const { data, headers } = res
      const encodedFilename = headers.get('download-filename').toString()
      const filename = decodeURIComponent(encodedFilename)
      downloadBlob(data, filename)
      message('导出成功！', { type: 'success' })
    })
    .catch((r) => {
      console.error(r)
      message('下载文件出现错误，请联系管理员！', { type: 'error' })
    })
    .finally(() => {
      downloadLoadingInstance.close()
    })
}
